package com.itheima.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/stu/*")
public class FilterStudent implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //中文乱码解决
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        ServletContext servletContext = req.getServletContext();
        //先进行默认用户登录，后续进行登录校验
        String lock = (String) servletContext.getAttribute("lock");
        if ("lock".equals(lock)){
            //放行
            filterChain.doFilter(req,resp);
        }else {
            //如果未登录，提示登录失败，进行定时跳转到登录页面
            resp.setHeader("Refresh","5;URL="+req.getContextPath()+"/login/login.jsp");
            //增加点击跳转方式
            resp.getWriter().write("<a href="+req.getContextPath()+"/login/login.jsp>如果未跳转到登录页面，可点击此链接进行跳转</a>");

        }
    }
}
